$NG.AllReady(function (page, { useBeforeClick, useValuesChange, useUpdateRows, useDataIndexChange }) {

    const mstform = $NG.getCmpApi("p_form_servicee_qs_m");
    const grid1 = $NG.getCmpApi("p_form_servicee_qs_d");


    if (page.oType != 'view') {
        cntMFilter()
        getPtInfoByPhid()
        getCntCount("p_form_servicee_qs_m", "u_cnt_name", cntMain)
        getXshtInPay()
        getProjectSybyTotalAmt()
        getZfdTotalAmt()
        getSjcztbTotalAmt()
        getFbyfdTotalAmtByPhidPc()
        GetIncomeCostData()
        getCgrkTotalAmt()
        getSbqdInitFromInfo()
        getSbqdHeadInfoByPhidPc()
        getSbqdTotalGapAmt()
        getLcbjhHkTotalAmt()
        getSjcztbTotalWsAmt()
        getCgyfdTotalAmt()
    }

    function getHeadVal(key){
        return mstform.getItem(key).getValue()
    }

    // 表头计算逻辑
    function sumAmtHead(map, exc) {
        const date = new Date()
        map.u_sfyq = (Number(map.u_dqgq) || 0) - (Number(map.u_htgq) || 0) > 0 ? '1' : '0'
        map.u_yhwhje = (Number(map.u_yhje) || 0) - (Number(map.u_yhkje) || 0)
        map.u_fbqf_amt = (Number(map.u_fbyfje) || 0) - (Number(exc.zfd_amt) || 0)
        map.u_dqwcl = (Number(map.u_htxe) || 0)?(Number(map.u_srqrje) || 0) / (Number(map.u_htxe) || 0):0
        map.u_srce = (Number(map.u_czby) || 0) - (Number(map.u_srqrje) || 0)
        map.u_sfcby = map.u_srce > 0?'0':'1'
        map.u_mllzj = (Number(map.u_ywghs) || 0) - (Number(map.u_ycztwgmll) || 0)
        map.u_ychtwcl = (Number(exc.init_ant_amy) || 0)?(Number(map.u_ychtezj) || 0) / (Number(exc.init_ant_amy) || 0):0
        map.u_cgqf_amt = (Number(exc.cgrk_amt) || 0) - (Number(exc.zfd_amt) || 0)
        map.bill_name = `${date.getFullYear()}-${String(date.getMonth() +1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}${mstform.getItem("phid_fill_psn").getText()}${mstform.getItem("phid_pc").getText()}成本核算`
    }

    // 表头赋值/计算(封装) 防止$NG.updateState异步赋值带来的取数错误
    $NG.setHeadValue = {}
    initHead('p_form_servicee_qs_m', sumAmtHead)
    function initHead(table, fun) {
        const mstform = $NG.getCmpApi(table);
        const val = mstform.getValues()
        const headKey = ["bill_name","u_cshte", "u_qdmll", "u_htxe", "u_qdbgje", "u_dqmjll", "u_yhje", "u_yhkje", "u_yhwhje", "u_cgyfje", "u_fbyfje", "u_czby",
            "u_dqwcl", "u_srqrje", "u_srce", "u_sfcby", "u_ywghs", "u_ywgmll", "u_mllzj", "u_ycztwg", "u_ycztwgmll", "u_ychtezj", "u_ychtwcl", "u_yjzjl"
            , "u_sfyq","u_zjl"]

        // 临时变量记录，不参与赋值(当缓存使用)可以参与表头计算
        const excludes = ["sjkgDt","zfd_amt","cgrk_amt", "sjcz_amt", "init_ant_amy"]

        // 劫持原表头赋值函数，防止2边数据不同步
        const option = $NG.updateState;
        $NG.updateState = function (...args) {
            const updater = args[0];
            args[0] = function (...innerArgs) {
                const targetObj = innerArgs[0].data[table];
                if (targetObj) {
                    const originalSetProps = targetObj.setProps;
                    targetObj.setProps = function (props) {
                        console.log(`劫持到的props`,props);
                        if (!props.hook) {
                            for (let key in props) {
                                if (headKey.includes(key)) {
                                    $NG.setHeadValue.manualSet(key, props[key]);
                                }
                            }
                        }
                        return originalSetProps.call(this, props);
                    };
                }
                return updater.apply(this, innerArgs);
            };

            option.apply(this, args); 
        };

        Object.defineProperties($NG.setHeadValue, {
            _sumAmt: { // 赋值渲染 + 表头计算计算
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key) { // 要跳过的key
                    const map = headKey.reduce((value, item) => {
                        value[item] = this["_" + item]
                        return value
                    }, {})
                    // 排除
                    const exclude = excludes.reduce((value, item) => {
                        value[item] = this["_" + item]
                        return value
                    }, {})
                    // 表头计算
                    fun(map, exclude)

                    if (key) {
                        delete map[key]
                    }
                    console.log(`赋值信息`, map, key);
                    $NG.updateState((updater) => {
                        updater.data[table].setProps({
                            hook: true,
                            ...map
                        })
                    })
                }
            },
            noRender: { // 不进行渲染赋值
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key, val) {
                    this["_" + key] = val
                }
            },
            manualSet: { // 禁止渲染手输入 但要计算
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key, val) {
                    this["_" + key] = val
                    this._sumAmt(key)
                }
            },
            manySetVal: { // 多字段赋值，类 _sunAmt
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (map) {
                    for (let key in map) {
                        this['_' + key] = map[key]
                    }
                    this._sumAmt()
                }
            }
        })
        // 创建不可枚举字段，让不加 _ 的变量代理私有属性(防异步)
        const ini = (item, bool) => {
            Object.defineProperties($NG.setHeadValue, {
                [item]: {
                    enumerable: true,
                    configurable: false,
                    set(val) {
                        console.log(`有key赋值了`,item,val);
                        this['_' + item] = val
                        if (window._sum_amt_lock) {
                            clearTimeout(window._sum_amt_lock)
                        }
                        window._sum_amt_lock = setTimeout(() => {
                            this._sumAmt()
                        }, 1000)
                    },
                    get() {
                        return this['_' + item]
                    }
                },
            })
            Object.defineProperties($NG.setHeadValue, {
                ["_" + item]: {
                    value: val[item],// 设置初始值
                    writable: true,
                    enumerable: false,
                    configurable: false,
                },
            })
            // 如果发生手输入改变
            if (bool) {
                useValuesChange(({ args }) => {
                    $NG.setHeadValue.manualSet(item, args[0][item])
                }, item)
            }
        }
        headKey.forEach(item => {
            ini(item, true)
        })
        excludes.forEach(el => {
            ini(el, false)
        })
    }

    // 合同入口
    function cntMain() {
        getCntMInfoByPhid()
        getProjectSybyTotalAmt()
        GetIncomeCostData()

    }

    useValuesChange(({ args }) => {
        getCntCount("p_form_servicee_qs_m", "u_cnt_name", cntMain)
        cntMFilter()
        getPtInfoByPhid()
        getFbyfdTotalAmtByPhidPc()
        getXshtInPay()
        getZfdTotalAmt()
        getSjcztbTotalAmt()
        getCgrkTotalAmt()
        GetIncomeCostData()
        getSbqdInitFromInfo()
        getSbqdHeadInfoByPhidPc()
        getSbqdTotalGapAmt()
        getLcbjhHkTotalAmt()
        getSjcztbTotalWsAmt()
        getCgyfdTotalAmt()
    }, "p_form_servicee_qs_m.phid_pc")

    useValuesChange(({ args }) => {
        cntMain()
    }, "p_form_servicee_qs_m.u_cnt_name")

    useUpdateRows(({args})=>{
        sumAmt(args[0])
        console.log(`useUpdateRows`,);
    },"p_form_servicee_qs_d")

    //合同根据项目ID过滤
    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_servicee_qs_m.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi('p_form_servicee_qs_m').getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi('p_form_servicee_qs_m').getItem('phid_pc').getValue() && {
                    clientSqlFilter: {
                        'pcm3_cnt_m.phid_pc': $NG.getCmpApi('p_form_servicee_qs_m').getItem('phid_pc').getValue(),
                        bill_type: 1,
                    }
                }),
            });
        });
    }
    
    function sumAmt(rows, add = false) {
        const syms = ['+', '-', '/', '*']
        // 需要计算的所有key
        const itemKeys = ['u_csys', 'u_bg', 'u_dqys', 'u_sjys', 'u_zmje', 'u_cq', 'u_zh', 'u_sjfs', 'u_jcb', 'u_cy', 'u_hxdfs', 'u_ztsj', 'u_yscy'];
        // 汇总行架构填写（自定义）(我未暂适配)括号优先级
        const sumMap = {
            '项目毛利': {
                exclude: [], // 排除列表（排除不计算的key）
                val: '收入 - 直接成本',  // 计算逻辑
            },
            '毛利率%': {
                exclude: [],
                val: '项目毛利 / 收入'
            }
        }
        rows.forEach(item => {
            item.u_cq = (Number(item.u_sjfs) || 0) - (Number(item.u_zmje) || 0)
            item.u_zh = Math.abs((Number(item.u_sjfs) || 0) - (Number(item.u_zmje) || 0))
            item.u_cy = (Number(item.u_sjys) || 0) - (Number(item.u_sjfs) || 0)
            item.u_ztsj = (Number(item.u_hxdfs) || 0) + (Number(item.u_sjfs) || 0)
            item.u_yscy = (Number(item.u_dqys) || 0) - (Number(item.u_ztsj) || 0)
        })
        rows.forEach(item => {
            const keys = Object.keys(sumMap)
            // 找需要计算的行
            if (keys.includes(item.u_qdxm)) {
                const val = sumMap[item.u_qdxm].val.replaceAll(' ', "")
                const exclude = sumMap[item.u_qdxm].exclude
                let init = 0
                let ind = 0
                let tempKey = ''
                let sys = ''
                for (const ve of val) {
                    ind++
                    (val.length == ind) && (tempKey += ve)
                    if (syms.includes(ve) || ind == val.length) {
                        // 查找相应数据
                        let it = rows.filter(ite => ite.u_qdxm == tempKey)
                        if (it.length == 0) {
                            throw (`填写sumMap计算有问题,${tempKey} ${val}未找到！`)
                        } else if (it.length != 1) {
                            throw (`填写sumMap计算有问题,${tempKey} ${val}发现多个！`) // 出现该错误表示清单项目重复
                        }
                        it = it[0]
                        if (init == 0) {
                            itemKeys.forEach(el => {
                                if (!exclude.includes(el)) {
                                    item[el] = (Number(it[el]) || 0)
                                }
                            })
                        } else {
                            switch (sys) {
                                case '+':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number(item[el]) || 0) + (Number(it[el]) || 0)
                                        }
                                    })
                                    break;
                                case '-':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number(item[el]) || 0) - (Number(it[el]) || 0)
                                        }
                                    })
                                    break;
                                case '/':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number((Number(item[el]) || 0) / (Number(it[el]) || 0)) || 0)
                                        }
                                    })
                                    break;
                                case '*':
                                    itemKeys.forEach(el => {
                                        if (!exclude.includes(el)) {
                                            item[el] = (Number((Number(item[el]) || 0) * (Number(it[el]) || 0)) || 0)
                                        }
                                    })
                                    break;
                            }
                        }
                        tempKey = ''
                        init++
                        sys = ve
                    } else {
                        tempKey += ve
                    }
                }
            }
        })

        rows.forEach(item=>{
            // 毛利部分
            if(item.u_qdxm == '毛利率%'){
                $NG.setHeadValue.u_ywghs = item.u_sjys
                $NG.setHeadValue.u_ycztwgmll = item.u_sjys
                // $NG.setHeadValue.u_yjzjl = item.u_yscy
                $NG.setHeadValue.u_ywgmll = item.u_sjfs
                
            } else if(item.u_qdxm == '直接成本'){
                $NG.setHeadValue.u_ycztwg = item.u_ztsj
                $NG.setHeadValue.u_ychtezj = item.u_yscy
            } else if (item.u_qdxm == '项目毛利'){
                let amt = (Number(item.u_sjfs) || 0) - (Number(item.u_sjys) || 0)
                $NG.setHeadValue.u_zjl = amt
                $NG.setHeadValue.u_yjzjl = item.u_yscy 
            } 
        })

        if (add) {
            grid1.clearRows().then(() => {
                grid1.addRows([...rows])
            })
        } else {
            grid1.refreshView()
        }
    }

    // 获取项目信息
    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                console.log("触发功能扩展:getPtInfoByPhid");
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`项目信息获取`, datas);
                $NG.updateState((updater) => {
                    //【注意这里的表名不能为控件ID，必须要是表名】
                    updater.data.p_form_servicee_qs_m.setProps({
                        u_pc_no: datas.pc_no,
                        //项目经理
                        phid_emp: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        phid_org:{
                            value:datas.org_phid,
                            label:datas.org_name
                        }
                        ,u_gcgk:datas.descript

                    });
                });
                if (!datas.fact_start_dt) {
                    $NG.alert("当前时间项目没有实际完成时间，当前工期无法计算！")
                }
                $NG.setHeadValue.sjkgDt = datas.fact_start_dt
            });
        }
    }

    // 获取合同信息
    function getCntMInfoByPhid() {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(`合同信息获取`, datas,datas.cnt_amt_init);
            // console.log(datas);
            $NG.updateState((updater) => {
                updater.data.p_form_servicee_qs_m.setProps({
                    u_cnt_no: datas.pcm_no, //合同编号
                    u_htxe: datas.cnt_sum_vat_fc, //合同价税合计
                    u_cshte: datas.init_cnt_amt,// 初始合同额
                    u_htgq: getDaysBetween(datas.start_dt, datas.end_dt),
                    u_dqgq: getDaysBetween($NG.setHeadValue.sjkgDt, new Date()),
                    

                });
                $NG.setHeadValue.init_ant_amy = datas.cnt_amt_init
            });
            // getQzInfo();
        });
    }
        // 获取设备清单初始单的数据
    function getSbqdInitFromInfo() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSbqdInitFromInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_qdmll = datas.u_signed_gm_rate
        })
    }

        // 获取设备清单表头信息
    function getSbqdHeadInfoByPhidPc() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSbqdHeadInfoByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_dqmjll = _data.u_signed_gm_rate
        })
    }

       // 获取设备清单变更签证变更金额
    function getSbqdTotalGapAmt() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSbqdTotalGapAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_qdbgje = _data.eq_total_amt_vat
        })
    }
    // 获取项目收入报验
    function getProjectSybyTotalAmt(){
        const cnt = getHeadVal("u_cnt_name")
        if(!cnt) return 
        $NG.execServer("getProjectSybyTotalAmt",{cnt},(res)=>{
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_srqrje = _data.total_amt
            // $NG.setHeadValue.u_yhje = _data.total_amt_vat
        })
    }

    // 获取销售合同收款的汇总值
    function getXshtInPay(){
        const phid_pc = getHeadVal("phid_pc")
        if(!phid_pc) return 
        $NG.execServer("getXshtInPay",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_yhkje = datas.total_amt
        })
    }

    // 获取分包应付单本次申请金额汇总
    function getFbyfdTotalAmtByPhidPc(){
        const phid_pc = getHeadVal("phid_pc")
        if(!phid_pc) return 
        $NG.execServer("getFbyfdTotalAmtByPhidPc",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_fbyfje = datas.hd_total_amt
        })
    }

    // 获取支付单已支付金额
    function getZfdTotalAmt(){
        const phid_pc = getHeadVal("phid_pc")
        if(!phid_pc) return 
        $NG.execServer("getZfdTotalAmt",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.zfd_amt = datas.total_amt
        })
    }

    // 获取实际产值填报
    function getSjcztbTotalAmt(){
        const phid_pc = getHeadVal("phid_pc")
        if(!phid_pc) return 
        $NG.execServer("getSjcztbTotalAmt",{phid_pc},(res)=>{
            if(res.count== 0 ) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.sjcz_amt = datas.total_amt
        })
    }

    // 获取时间产值填报未税金额
    function getSjcztbTotalWsAmt(){
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if(!phid_pc) return 
        $NG.execServer("getSjcztbTotalWsAmt",{phid_pc},(res)=>{
            if(res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_czby = datas.ljcz_ws
        })
    }

    // 获取采购应付单 厚款
    function getCgyfdTotalAmt(){
        const phid_pc = getHeadVal("phid_pc")
        if(!phid_pc) return 
        $NG.execServer("getCgyfdTotalAmt",{phid_pc},(res)=>{
            if(res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_cgyfje = datas.total_amt
        })
    }

    // 获取采购入库的合计金额
    function getCgrkTotalAmt(){
        const phid_pc = getHeadVal("phid_pc")
        if(!phid_pc) return 
        $NG.execServer("getCgrkTotalAmt",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.cgrk_amt = datas.total_amt
        })
    }

    // 成本核算分析
    function GetIncomeCostData() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        const cnt = mstform.getItem("u_cnt_name").getValue()
        console.log(`获取核算信息`, phid_pc, cnt);
        if (!cnt || !phid_pc) return
        $NG.execServer("GetIncomeCostData", { pc: phid_pc, cnt: cnt }, (res) => {
            if (res.count == 0) return
            const data = JSON.parse(res.data).reduce((value, items) => {
                const item = items.extendObjects
                const map = {
                    u_qdxm: item.qdxm,
                    u_csys: item.csys,
                    u_bg: item.bg,
                    u_dqys: item.dqys,
                    u_sjys: item.sjys,
                    u_zmje: item.zmje,
                    u_sjfs: item.sjfs,
                    u_jcb: item.jcb,
                }
                value.push(map)
                return value
            }, [])
            sumAmt(data, true)
        })
    }
    // 获取里程碑计划的回款明细
    function getLcbjhHkTotalAmt(){
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if(!phid_pc) return 
        $NG.execServer("getLcbjhHkTotalAmt",{phid_pc},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_yhje = datas.yhk_total_amt
        })
    }

    //获取合同数量
    function getCntCount(table, key, fun, otherFun) {
        if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
        $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
            switch (res.count) {
                case 0:
                    return;
                case 1:
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    const temp_map = {};
                    temp_map[key] = datas.phid;
                    temp_map[`${key}_EXName`] = datas.bill_name;
                    $NG.updateState((updater) => {
                        updater.data[table].setProps({
                            ...temp_map,
                        });
                        setTimeout(() => {
                            fun();
                            if (otherFun) {
                                otherFun();
                            }
                        }, 200);
                    });
            }
        });
    }


    // utils
    function getDaysBetween(d1, d2) {
        const parseDate = (d) => {
            if (d instanceof Date) {
                return d;
            } else if (typeof d === 'string' || typeof d === 'number') {
                const parsed = new Date(d);
                if (!isNaN(parsed)) return parsed;
            }
            return null
        };

        const date1 = parseDate(d1);
        const date2 = parseDate(d2);
        if (!date1 || !date2) {
            return 0
        }

        const diffTime = date2.getTime() - date1.getTime();
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        return diffDays;
    }
})